package comply.zyc.controller;

import comply.zyc.Ku;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

/**
 * @description:
 * @author: ZhaoYicong
 * @date: Created in 2020/6/21 22:29
 * @version: v1.0
 * @modified By:
 */

@WebServlet("/login")
   //登录页面的逻辑处理层
public class LoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //通关请求获取传过来的参数
        String nameby=req.getParameter("username");
        String passwordby=req.getParameter("password");

        Cookie c = null;
//        Cookie cookie = new Cookie("username", null);
//        cookie.setMaxAge(0);
//        cookie.setPath("/test/test2");



        try {
            //实现对应的sql  语法和防止 sql注入
            Connection connection= Ku.getConnection();
            PreparedStatement stmt = connection.prepareStatement("select * from loding where name=?");
            stmt.setString(1,nameby);
            ResultSet resultSet = stmt.executeQuery();

            //对应的逻辑判断。
           if(!resultSet.next()){
               String result="用户名不存在";
               req.setAttribute("result",result);
               req.getRequestDispatcher("login.jsp").forward(req,resp);
               return;

           }

            String pwd=resultSet.getString("password");
            if (passwordby.equals(pwd)){



                c=new Cookie("username",nameby);
                c.setMaxAge(60);

                resp.addCookie(c);


//
//                req.getSession().setAttribute("username",nameby);
//                resp.sendRedirect("home.jsp");
                req.setAttribute("username",nameby);
                req.getRequestDispatcher("home.jsp").forward(req,resp);
            }else{
                String result="密码错误";
                req.setAttribute("result",result);
                req.getRequestDispatcher("login.jsp").forward(req,resp);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }



    }
}
